package com.cui.demoshiro.controller;

import com.cui.demoshiro.pojo.Role;
import com.cui.demoshiro.pojo.User;
import com.cui.demoshiro.service.role.RoleService;
import com.cui.demoshiro.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private RoleService roleService ;

    @Resource
    private UserService userService ;

    @RequestMapping("/userList")
    @RequiresPermissions("userList")
    public String userList(Model model) {

        List<User> userList = userService.getAllUsers() ;
        model.addAttribute("userList", userList) ;

        return "user/userList" ;
    }

    @RequestMapping("/userAdd")
    @RequiresPermissions("userAdd")
    public String userAdd(Model model) {
        List<Role> roleList = roleService.getAllRoles() ;
        model.addAttribute("roleList", roleList) ;

        return "user/userAdd" ;
    }

    @RequestMapping("/doUserAdd")
    @RequiresPermissions("userAdd")
    public String doUserAdd(User user, int[] roles, Model model) {

        User userInfo = (User) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        System.out.println(userInfo.getId()+"=============================");

        System.out.println(user.toString());
        System.out.println(roles.length);

        int success = userService.addUser(user, roles) ;
        String msg = "" ;
        if(success == 1) {
            msg = "添加用户成功" ;
        }
        else {
            msg = "添加用户失败" ;
        }
        model.addAttribute("msg",msg) ;

        return "forward:/user/userAdd" ;
    }


    @GetMapping("/userEdit/{uid}")
    @RequiresPermissions("userEdit")
    public String userEdit(@PathVariable("uid") int uid, Model model) {
        User user = userService.getUserById(uid) ;
        model.addAttribute("user", user) ;

        List<Role> roleList = roleService.getAllRoles() ;
        model.addAttribute("roleList", roleList) ;

        return "user/userEdit" ;
    }

    @PostMapping("/doUserEdit")
    @RequiresPermissions("userEdit")
    public String doUerEdit(User user, int[] roles, Model model) {

        //暂不实现，记住原则，修改用户之前，需将用户角色中间表根据用户id删除，然后重新分配角色

        return "user/userList" ;
    }
}
